﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;
using System.Xml.Serialization;

namespace GoogleFuns
{
    public class GoogleWeather
    {
        /// <summary>
        /// 按地区
        /// </summary>
        /// <param name="AddressCode">Drammen</param>
        /// <returns></returns>
        public GWeather GetWeather(string AddressCode)
        {
            string strUrl = @"http://www.google.co.uk/ig/api?weather=" + AddressCode;
            GWeather gWeather = GoogleWeatherAPI_Parser(strUrl);
            return gWeather;
        }
        /// <summary>
        /// 按经纬度查询
        /// </summary>
        /// <param name="AddressCode"></param>
        /// <returns></returns>
        public GWeather GetWeatherLatLon(double lat, double lon)
        {
            string strUrl = @"http://www.google.co.uk/ig/api?weather=,,," + lat.ToString("f6").Replace(".","") + ","
                + lon.ToString("f6").Replace(".","");
            GWeather gWeather = GoogleWeatherAPI_Parser(strUrl);
            return gWeather;
        }

        private GWeather GoogleWeatherAPI_Parser(string baseUrl)
        {
            HttpWebRequest GWP_Request;
            HttpWebResponse GWP_Response = null;
            GWeather gWeather = null;
            try
            {
                GWP_Request = (HttpWebRequest)WebRequest.Create(string.Format(baseUrl));
                GWP_Request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4";
                GWP_Response = (HttpWebResponse)GWP_Request.GetResponse();
                Stream dataStream = GWP_Response.GetResponseStream();
                XmlSerializer ser = new XmlSerializer(typeof(GWeather));
                gWeather = (GWeather)ser.Deserialize(dataStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            GWP_Response.Close();
            return gWeather;
        }

    }
}
